package com.mew.chess.core.common.handler;


import cn.hutool.core.util.StrUtil;
import com.mew.common.dc.redis.AucRedisService;
import com.mew.common.dc.redis.GameRoomRedisService;
import com.mew.common.enm.DataStateType;
import com.mew.common.entity.config.Room;
import com.mew.common.rest.bo.GameSession;
import com.zebra.common.OnlineType;
import com.zebra.common.ZebraException;
import com.zebra.remoting.config.BasisCommandCode;
import com.zebra.remoting.config.EmptyMessage;
import com.zebra.remoting.config.TmsServerInfo;
import com.zebra.remoting.tms.TmsConfigInfoManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class GameCommonService {

    @Autowired
    private AucRedisService aucRedisService;
    @Autowired
    private GameRoomRedisService gameRoomRedisService;

    public void checkTMSOnline(List<GameSession> list, int gameId, int roomId){
        TmsServerInfo tmsServerInfo = TmsConfigInfoManager.getInstance().getServerInfo();
        if (tmsServerInfo.getOnline() < OnlineType.Online.value()){
            log.info("****TMS not online {}", tmsServerInfo.toString());
             doGameOverExit(list,  0);
             return;
        }

        if (aucRedisService.getMaintenance()){
            log.info("**** SYS  maintenance ******");
            doGameOverExit(list,  1);
            return;
        }

        Room room = gameRoomRedisService.getRedisRoom(gameId, roomId);
        if (null == room || DataStateType.Delete.code() == room.getState()){
            log.error("***** Room close gameId {} roomId {}", gameId, roomId);
            doGameOverExit(list,  1);
        }

    }

    private void doGameOverExit(List<GameSession> list, int type){
        if (null == list || list.isEmpty()){
            return;
        }

        GameSession gameSession = list.get(0);
        try {
            ChessEEHandler chessEEHandler = InitializeEEHandlerMapping.getMapping(gameSession.getVfx());
            for (GameSession v : list){
                if (v.getWhiteList() == 0){
                    ChessPushMessageUtil.pushMessage(v, BasisCommandCode.OVERHAULED.cmd(), new EmptyMessage());
                    chessEEHandler.expiredExit(v.getUserId(), v.getGameId(), v.getRoomId());
                    if (0 == type){
                        aucRedisService.offlineSession(v.getUserId());
                    }
                }
            }
        } catch (ZebraException e) {
            log.error(StrUtil.format("***CheckTMSOnline Exception g {}, r {}", gameSession.getVfx(), gameSession.getRoomId()), e);
        }
    }
}
